<template>
  <div>
    <div class="material" v-if="!materialAddShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:material:query']"
          class="btn search"
          @click="getMaterialList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['system:material:add']"
          class="btn search"
          @click="
            materialAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="materialPicture">物料图片</el-checkbox>
            </div>
            <div>
              <el-checkbox label="materialCode">物料编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="materialName">物料简称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="importantDevice">是否为贵重物品</el-checkbox>
            </div>
            <div>
              <el-checkbox label="factoryCode">出厂型号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="technologyParameter">技术参数</el-checkbox>
            </div>
            <div>
              <el-checkbox label="materialUnitName">单位</el-checkbox>
            </div>
            <div>
              <el-checkbox label="categoryName">物料分类</el-checkbox>
            </div>
            <!-- <div>
              <el-checkbox label="stockTypeName">存货类型</el-checkbox>
            </div> -->
            <div>
              <el-checkbox label="warningNumber">产品预警数量</el-checkbox>
            </div>
            <div>
              <el-checkbox label="distributorName">供应商</el-checkbox>
            </div>
            <div>
              <el-checkbox label="productionName">生产厂商</el-checkbox>
            </div>
            <div>
              <el-checkbox label="firstPurchaseTime">首次采购时间</el-checkbox>
            </div>
         
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.materialCode"
            class="search-input"
            maxlength="30"
            placeholder="请输入物料编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.materialName"
            class="search-input"
            maxlength="30"
            placeholder="请输入物料简称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.factoryCode"
            class="search-input"
            maxlength="30"
            placeholder="请输入出厂型号"
          ></el-input>
        </div>
        <!-- <div class="search-item">
          <el-input
            clearable
            v-model="params.supplierName"
            class="search-input"
            maxlength="30"
            placeholder="请输入供应商名称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.name"
            class="search-input"
            maxlength="30"
            placeholder="请输入生产厂商名称"
          ></el-input>
        </div> -->
        <!-- <div class="search-item">
          <el-select
            v-model="params.stockType"
            placeholder="请选择存货类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in stockTypeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div> -->
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.supplierName"
            class="search-input"
            maxlength="30"
            placeholder="请输入供应商名称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.manufactureName"
            class="search-input"
            maxlength="30"
            placeholder="请输入生产厂商"
          ></el-input>
        </div>
      </div>
      <div class="material-container">
        <!--分类数据-->
        <div class="class-container">
          <div class="class-top">
            <el-input
              v-model.trim="className"
              placeholder="搜索分类"
              clearable
              class="class-input"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="classOptions"
              :props="{ label: 'categoryName', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="id"
              :highlight-current="true"
              default-expand-all
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <span
                  class="span-ellipsis"
                  :title="node.label.length > 18 ? node.label : ''"
                  >{{ node.label }}
                  <el-icon
                    v-if="data.importantDevice == 1"
                    style="margin-left: 5px; transform: translateY(2px)"
                    title="贵重设备"
                    color="#FF9552"
                    :size="15"
                  >
                    <Box />
                  </el-icon>
                </span>
              </template>
            </el-tree>
          </div>
        </div>
        <div style="width: 85%">
          <!-- 表格数据 -->
          <el-table
            v-loading="loading"
            :data="materialList"
            border
            height="64vh"
            :header-cell-style="{ 'text-align': 'center' }"
            @sort-change="sortChange"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              :show-overflow-tooltip="true"
              width="140px"
            >
              <template #default="{ row }">
                <div class="table-operate">
                  <el-icon
                    v-hasPermi="['system:material:edit']"
                    title="编辑"
                    color="#FFB700"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('edit', row)"
                  >
                    <Edit />
                  </el-icon>
                  <el-icon
                    v-hasPermi="['system:material:detail']"
                    title="查看详情"
                    color="#007CEF"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('detail', row)"
                  >
                    <Document />
                  </el-icon>
                  <el-icon
                    v-hasPermi="['system:material:remove']"
                    title="删除"
                    color="#E33838"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('delete', row)"
                  >
                    <Delete />
                  </el-icon>
                </div> </template
            ></el-table-column>
            <el-table-column
              type="index"
              label="序号"
              :index="indexMethod"
              width="70"
              align="center"
            />
            <el-table-column
              label="物料图片"
              prop="materialPicture"
              :show-overflow-tooltip="true"
              min-width="120"
              align="center"
              v-if="checkList.includes('materialPicture')"
            >
              <template #default="{ row }">
                <el-image
                  :preview-teleported="true"
                  style="width: 50px; height: 50px; margin: 0 auto"
                  :src="row.materialPicture"
                  :preview-src-list="showImg(row.materialPicture)"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><icon-picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column
            v-if="checkList.includes('materialCode')"
              label="物料编号"
              prop="materialCode"
              :show-overflow-tooltip="true"
              min-width="120"
              sortable="custom"
            >
              <template #default="{ row }">
                <span>{{ row.materialCode ? row.materialCode : "--" }}</span>
              </template>
            </el-table-column>
            <el-table-column
            v-if="checkList.includes('materialName')"
              label="物料简称"
              prop="materialName"
              :show-overflow-tooltip="true"
              min-width="180"
              sortable="custom"
            >
              <template #default="{ row }">
                <span class="ellipsisStyle">{{
                  row.materialName ? row.materialName : "--"
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
            v-if="checkList.includes('importantDevice')"
              label="是否为贵重物品"
              prop="importantDevice"
              :show-overflow-tooltip="true"
              min-width="160"
              sortable="custom"
            >
              <template #default="{ row }">
                <span>{{ row.importantDevice == 1 ? "是" : "否" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="出厂型号"
              prop="factoryCode"
              :show-overflow-tooltip="true"
              min-width="120"
              v-if="checkList.includes('factoryCode')"
              sortable="custom"
            />
            <el-table-column
              label="技术参数"
              prop="technologyParameter"
              :show-overflow-tooltip="true"
              min-width="120"
              v-if="checkList.includes('technologyParameter')"
              sortable="custom"
            />
            <el-table-column
              label="单位"
              prop="materialUnitName"
              :show-overflow-tooltip="true"
              min-width="120"
              v-if="checkList.includes('materialUnitName')"
              sortable="custom"
            />
            <el-table-column
              label="物料分类"
              prop="categoryName"
              :show-overflow-tooltip="true"
              min-width="120"
              v-if="checkList.includes('categoryName')"
              sortable="custom"
            />
            <!-- <el-table-column
              label="存货类型"
              prop="stockTypeName"
              :show-overflow-tooltip="true"
              min-width="120"
              v-if="checkList.includes('stockTypeName')"
              sortable="custom"
            /> -->
            <el-table-column
              label="产品预警数量"
              prop="warningNumber"
              :show-overflow-tooltip="true"
              min-width="150"
              v-if="checkList.includes('warningNumber')"
              sortable="custom"
            />
            <el-table-column
              label="供应商"
              prop="supplierName"
              :show-overflow-tooltip="true"
              min-width="200"
              v-if="checkList.includes('distributorName')"
              sortable="custom"
            >
              <template #default="{ row }">
                <span class="ellipsisStyle">{{
                  row.supplierName ? row.supplierName : "--"
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="生产厂商"
              prop="manufactureName"
              :show-overflow-tooltip="true"
              min-width="200"
              v-if="checkList.includes('productionName')"
              sortable="custom"
            >
              <template #default="{ row }">
                <span class="ellipsisStyle">{{
                  row.manufactureName ? row.manufactureName : "--"
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="首次采购时间"
              prop="firstPurchaseTime"
              :show-overflow-tooltip="true"
              min-width="150"
              v-if="checkList.includes('firstPurchaseTime')"
              sortable="custom"
            />
          </el-table>
        </div>
      </div>
      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getMaterialList"
      />
    </div>
    <MaterialAdd
      v-if="materialAddShow"
      ref="materialAddRef"
      v-model:materialAddShow="materialAddShow"
      @refreshList="getMaterialList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
import { Picture as IconPicture } from "@element-plus/icons-vue";
import MaterialAdd from "./materialAdd";
const { proxy } = getCurrentInstance();
import { getDictsApi } from "@/api/dict";
import { getMaterialClassListApi } from "@/api/information/materialClass";
import {
  getMaterialListApi,
  deleteMaterialApi,
} from "@/api/information/material";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
// 搜索参数
const params = reactive({
  categoryId: null,
  factoryCode: "",
  materialCode: "",
  materialName: "",
  stockType: null,
  supplierName: "",
  manufactureName: "",
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});
const checkList = ref([
  "materialPicture",
  "materialCode",
  "materialName",
  "importantDevice",
  "factoryCode",
  "technologyParameter",
  "materialUnitName",
  "categoryName",
  "stockTypeName",
  "warningNumber",
  "distributorName",
  "productionName",
  "firstPurchaseTime",
]);


// 表格加载效果
const loading = ref(false);
// 物料新增组件显隐
const materialAddShow = ref(false);
// 物料列表
const materialList = ref([]);
// 总数
const total = ref(0);
// 分类名称
const className = ref("");
// 物料新增组件引用
const materialAddRef = ref(null);
// 操作类型
const pageType = ref("");
// 存货类型列表
const stockTypeList = ref([]);
// 分类列表
const classOptions = ref(undefined);
//默认选中
const deptTreeRef = ref(null);

/**
 * @description: 复选框选中
 */
 const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: 4,
    titleField: str,
  });
  // getTableHeader();
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 4,
  });
  if (result.code == 200 && result.data.titleField) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 获取物料列表
 */
const getMaterialList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    const res = await getMaterialListApi({ pageNum, pageSize }, params);
    materialList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
 const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getMaterialList();
};

/**
 * @description: 重置
 */
 const handleRefresh = () => {
  Object.assign(params, {
    categoryId: null,
  factoryCode: "",
  materialCode: "",
  materialName: "",
  stockType: null,
  supplierName: "",
  sortField: "",
  sortOrder: "",
  manufactureName: "",
    pageNum: 1,
    pageSize: 50,
  });
  getMaterialList()
};

/**
 * @description: 获取分类列表
 */
const getMaterialClassList = async () => {
  const res = await getMaterialClassListApi({ pageNum: 1, pageSize: 50 });
  let obj = [
    {
      categoryId: 0,
      categoryName: "全部",
      parentId: null,
      children: [],
      id: 0,
    },
  ];
  res.rows.forEach((item) => {
    item.id = item.categoryId;
  });
  let treeData = proxy.handleTree(res.rows, "id");
  obj[0].children.push(...treeData);
  classOptions.value = obj;
  // 设置默认选中的节点的 key 值
  setTimeout(() => {
    deptTreeRef.value.setCurrentKey(0);
  }, 0);
};



/**
 * @description: 通过条件过滤节点
 * @param {String} value 分类名称
 * @param {Object} data 数据源
 *
 */
const filterNode = (value, data, node) => {
  //保留有关键字的
  // if (!value) return true;
  // return data.categoryName.indexOf(value) !== -1;

  //保留搜索到的父级和子级
  if (!value) return true;
  let _array = []; //这里使用数组存储 只是为了存储值。
  getReturnNode(node, _array, value);
  let result = false;
  _array.forEach((item) => {
    result = result || item;
  });
  return result;
};

const getReturnNode = (node, _array, value) => {
  let isPass =
    node.data &&
    node.data.categoryName &&
    node.data.categoryName.indexOf(value) !== -1;
  isPass ? _array.push(isPass) : "";
  if (!isPass && node.level != 1 && node.parent) {
    getReturnNode(node.parent, _array, value);
  }
};
/**
 * @description: 监听分类名称
 * @param {String} val 变更后分类名称
 */
watch(className, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/**
 * @description: 节点单击事件
 * @param {Object} data 数据源
 */
function handleNodeClick(data) {
  if (!data.id) {
    params.categoryId = null;
  } else {
    params.categoryId = data.id;
  }
  getMaterialList();
}

/**
 * @description: 预览照片
 * @param {String} img 图片地址
 */
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "detail":
      materialAddShow.value = true;
      pageType.value = "detail";
      nextTick(() => {
        materialAddRef.value.handleDetailInfo(row.materialId);
      });
      break;
    case "edit":
      materialAddShow.value = true;
      pageType.value = "edit";
      nextTick(() => {
        materialAddRef.value.handleDetailInfo(row.materialId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该物料，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteMaterialApi(row.materialId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getMaterialList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 存货类型
  // await getDictsApi("stock_type").then((res) => {
  //   if (res.code === 200) {
  //     stockTypeList.value = res.data;
  //   }
  // });
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  getTableHeader();
  getMaterialList();
  getMaterialClassList();
  getDicts();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.material {
  padding: 20px 20px;
  width: 100%;
  height: 100%;

  .material-container {
    display: flex;

    .class-container {
      width: 240px;
      margin-right: 10px;
      padding-top: 30px;
      background: #ffffff;
      box-shadow: 0px 0px 10px 0px rgba(26, 43, 26, 0.1);
      border-radius: 2px;
      overflow: auto;
      .class-top {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;
        .class-input {
          width: 180px;
        }
      }
    }
    .span-ellipsis {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .pagination {
    margin: 20px auto;
  }
  :deep(.el-table) {
    .el-table__cell {
      padding: 0;
      height: 40px;
    }
    .cell.el-tooltip {
      display: flex;
      align-items: center;
    }
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
  }
  .image-slot .el-icon {
    font-size: 30px;
  }
}
</style>
